<template>
  <div>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="标题" prop="title">
        <el-input v-model="formData.title" placeholder="请输入标题" :disabled="showEdit" />
      </el-form-item>
      <el-form-item label="图集" prop="urls">
        <div>
          <el-radio-group
            v-if="formData.urls.length == 0"
            v-model="imageType"
            @change="handleImageTypeChange"
            :disabled="showEdit"
          >
            <el-radio :label="0">上传</el-radio>
            <el-radio :label="1">选择</el-radio>
          </el-radio-group>
          <UploadImgs
            v-if="imageType == 0 || formData.urls.length > 0"
            v-model="formData.urls"
            :limit="100"
            height="200px"
            width="200px"
            :disabled="showEdit"
          />
        </div>
      </el-form-item>
      <el-form-item>
        <!-- <el-button type="primary" @click="submitForm">修改</el-button> -->
        <el-button v-if="showEdit" type="primary" @click="showEdit = false">修改</el-button>
        <el-button v-if="!showEdit" type="primary" @click="submitForm">保存</el-button>
      </el-form-item>
    </el-form>
    <ChooseImage ref="chooseImageRef" @choose="chooseImageChange"/>
  </div>
</template>
<script setup lang="ts">
import { ContentImageApi, ContentImageVO } from '@/api/cms/contentimage'
import ChooseImage from './ChooseImage.vue'

/** 文本内容 表单 */
defineOptions({ name: 'ContentImage' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const showEdit = ref(true)

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const imageType = ref(0)
const dialogImageVisible = ref(false) // 弹窗的是否展示
const chooseImageRef = ref() // 表单 Ref
const formData = ref({
  id: undefined,
  menuId: undefined,
  title: undefined,
  urls: [],
  url: undefined,
  status: undefined
})
const formRules = reactive({
  menuId: [{ required: true, message: '菜单ID不能为空', trigger: 'blur' }],
  title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
  urls: [{ required: true, message: '图集不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (menuId) => {
  dialogVisible.value = true
  resetForm()
  // 修改时，设置数据
  if (menuId) {
    formLoading.value = true
    try {
      formData.value = (await ContentImageApi.getByMenuId(menuId)) || {}
      if (formData.value.id) {
        formData.value.urls = formData.value.url.split(',') || []
      } else {
        formData.value.menuId = menuId
      }
    } finally {
      formLoading.value = false
    }

    showEdit.value = true
  } else {
    formData.value.menuId = menuId
    showEdit.value = false
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value
    data.url = formData.value.urls.join(',')
    if (data.id) {
      await ContentImageApi.updateContentImage(data)
      message.success(t('common.updateSuccess'))
    } else {
      await ContentImageApi.createContentImage(data)
      message.success(t('common.createSuccess'))
    }
    showEdit.value = true
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    menuId: undefined,
    title: undefined,
    urls: [],
    url: undefined,
    status: undefined
  }
  formRef.value?.resetFields()
}

const handleImageTypeChange = (val) => {
  imageType.value = val
  if (val == 1) {
    chooseImageRef.value.open(1)
  }
}

const chooseImageChange = (data) => {
  console.log('formData.value.urls', formData.value.urls)
  formData.value.urls = data
}
</script>